#import "CustomColorManager.h"

#define kCustomColorsKey @"CustomColorsKey"

@implementation CustomColorManager

+ (NSArray<UIColor *> *)loadCustomColors {
    NSArray *colorHexes = [[NSUserDefaults standardUserDefaults] objectForKey:kCustomColorsKey];
    NSMutableArray *colors = [NSMutableArray array];
    for (NSString *hex in colorHexes) {
        UIColor *color = [self colorFromHex:hex];
        if (color) [colors addObject:color];
    }
    return colors;
}

+ (void)saveCustomColors:(NSArray<UIColor *> *)colors {
    NSMutableArray *hexes = [NSMutableArray array];
    for (UIColor *color in colors) {
        NSString *hex = [self hexFromColor:color];
        if (hex) [hexes addObject:hex];
    }
    [[NSUserDefaults standardUserDefaults] setObject:hexes forKey:kCustomColorsKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - Color <-> Hex
+ (NSString *)hexFromColor:(UIColor *)color {
    CGFloat r, g, b, a;
    if ([color getRed:&r green:&g blue:&b alpha:&a]) {
        int ri = (int)(r * 255);
        int gi = (int)(g * 255);
        int bi = (int)(b * 255);
        return [NSString stringWithFormat:@"#%02X%02X%02X", ri, gi, bi];
    }
    return nil;
}
+ (UIColor *)colorFromHex:(NSString *)hex {
    unsigned int rgb = 0;
    if ([[NSScanner scannerWithString:[hex stringByReplacingOccurrencesOfString:@"#" withString:@""]] scanHexInt:&rgb]) {
        return [UIColor colorWithRed:((rgb>>16)&0xFF)/255.0 green:((rgb>>8)&0xFF)/255.0 blue:(rgb&0xFF)/255.0 alpha:1.0];
    }
    return nil;
}
@end 